<?php

namespace Hilaoyu\LaravelExtend\Services\Files;



use Hilaoyu\LaravelExtend\Traits\ModelVirtualTrait;
use Hilaoyu\Utils\UtilFile;
use Illuminate\Support\Str;

class FilesVirtualModel extends FilesModelAbstract
{
    protected $connection = null;
    protected $table = null;



    protected function _getSavePath($key=''){
        $path = config('file_service.files_task_path',storage_path('_files_task_path'));
        $path = rtrim($path,'/');
        $path = rtrim($path,'\\');
        if($key){
            $path .= DIRECTORY_SEPARATOR . UtilFile::dirNameToHash($key);
        }
        $path .= '.fsm';
        return $path;
    }

    public function save(array $options = [])
    {
        if ($this->fireModelEvent('saving') === false) {
            return false;
        }
        if(!$key = $this->getKey()){
            return false;
        }
        $hidden = $this->getHidden();
        $appends = $this->appends;
        $this->setHidden([]);
        $this->setAppends([]);

        $save_path = $this->_getSavePath($key);
        if(!UtilFile::checkDir(UtilFile::dirname($save_path))){
            $this->setError('存储目录不可写');
            return false;
        }

        $saved = file_put_contents($this->_getSavePath($key),json_encode($this->attributesToArray()));
        $this->setHidden($hidden);
        $this->setAppends($hidden);
        if($saved){
            $this->syncOriginal();
            //$this->exists = true;
            $this->fireModelEvent('saved', false);
        }

        return $saved;
    }

    public function update(array $attributes = [], array $options = [])
    {
        if ($this->fireModelEvent('updating') === false) {
            return false;
        }
        $saved = $this->fill($attributes)->save($options);
        if($saved){
            $this->fireModelEvent('updated', false);
        }

        return $saved;
    }

    public function delete()
    {
        if ($this->fireModelEvent('deleting') === false) {
            return false;
        }
        if(!$key = $this->getKey()){
            return false;
        }

        @unlink($this->_getSavePath($key));

        $this->fireModelEvent('deleted', false);
        return true;
    }

    public function find($id){
        $task_file_path = $this->_getSavePath($id);

        if(file_exists($task_file_path)){
            $attributes = json_decode(file_get_contents($task_file_path),true);
            if($attributes){
                $model = new static();
                $model->forceFill($attributes);
                $model->syncOriginal();
                //$model->exists = true;
                return $model;
            }
            return null;
        }

        return static::loadCacheModel($id);
    }
    
}
